package com.singfan.core.dao.database.impl;

import com.singfan.common.db.DaoBaseGeneric;
import com.singfan.core.dao.database.ICustomerCouponDao;
import com.singfan.core.dao.database.model.CustomerCoupon;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

/**
 * Author: hansonghe
 * Date: 2015-09-15 12:20
 * Desc:
 */
@Repository
public class CustomerCouponDaoImpl extends DaoBaseGeneric<CustomerCoupon> implements ICustomerCouponDao {
    @Override
    protected String getTableName(Object hashKey) {
        return tableNameBase;
    }

    @Override
    protected String getDatabaseId(Object hashKey) {
        return "app_1";
    }

    @Override
    public void create(CustomerCoupon customerCoupon) {
        insertWithAutoIncrement(null, customerCoupon);
    }

    @Override
    public List<CustomerCoupon> selectListByCustomerId(long customerId, boolean isExpired, int pageIndex, int pageSize) {
        String sql;
        if (isExpired){
            sql = "SELECT * FROM " + getTableName(null) + " WHERE customer_id=? AND expired_time<? AND order_id=0 ORDER BY create_time DESC limit ?,?";
        }
        else {
            sql = "SELECT * FROM " + getTableName(null) + " WHERE customer_id=? AND expired_time>? AND order_id=0 ORDER BY create_time DESC limit ?,?";
        }

        return selectList(null, sql, customerId, new Date(), pageIndex * pageSize, pageSize);
    }

    @Override
    public CustomerCoupon selectById(long couponId) {
        return selectByPK(null, couponId);
    }

    @Override
    public void deleteByOrderId(long orderId) {
        String sql = "DELETE FROM " + getTableName(null) + " WHERE order_id=?";
        execute(null, sql, orderId);
    }

    public void setOrderId(long couponId, long orderId){
        String sql = "UPDATE " + getTableName(null) + " SET order_id=? WHERE id=?";
        execute(null, sql, orderId, couponId);
    }

    @Override
    public void cancelOrderId(long orderId) {
        String sql = "UPDATE " + getTableName(null) + " SET order_id=0 WHERE order_id=?";
        execute(null, sql, orderId);
    }

    @Override
    public void deleteByCouponId(long couponId) {
        String sql = "DELETE FROM " + getTableName(null) + " WHERE coupon_record_id=?";
        execute(null, sql, couponId);
    }
}
